﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using sgsBase;

namespace TestApp.Account
{
    public partial class PasswordReset : SgsPage
    {
		string _continueUrl = "";
		string _id = "";

        protected override void PageLoad(object sender, EventArgs e)
        {
            //RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
			_continueUrl = Request.QueryString["ReturnUrl"];
			_id = CheckFormvar("id");

			//use the hashcode to find and set the current user, otherwise report it as a bad hashcode.
			if (_id == "")
			{
				AddMessage("Incorrect or invalid request.");
				return;
			}

			if (!IsPostBack)
			{
				DbUsrPasswordReset upr = new DbUsrPasswordReset();
				upr.HashCode = _id;
				if (!upr.Select())
				{
					AddMessage("Incorrect attempt. Please copy and paste the given URL into your browser address bar.");
					return;
				}
				if (upr.DtCompleted != DateTime.MinValue)
				{
					AddMessage("Request has already been used to reset password. Please re-request a password reset.");
					Response.Redirect("~/Account/forgot.aspx");
					return;
				}
				DbUsrUser uu = new DbUsrUser();
				uu.UserId = upr.UserId;
				if (uu.Select())
				{
					txEmail.Text = uu.LoginId;
				}
				Gl.CurUser.ID = 0;
			}
        }

		//protected void RegisterUser_OnCreatingUser(object sender, LoginCancelEventArgs e)
		protected void ResetPasswordButton_Click(object sender, EventArgs e)
		{
			DbUsrPasswordReset upr = new DbUsrPasswordReset();

			upr.HashCode = _id;
			if (!upr.Select())
			{
				AddMessage("Incorrect attempt. Please copy and paste the given URL into your browser address bar.");
				return;
			}
			//uu.LoginPass = Password.Text;
			upr.DtCompleted = DateTime.Now;
			upr.Update();

			Gl.CurUser.Logout();
			DbUsrUser uu = new DbUsrUser();
			uu.UserId = upr.UserId;
			uu.Select();
			uu.LoginPass = Password.Text;
			uu.Update();

			Gl.CurUser.Login(upr.UserId);
	
			//Gl.CurUser.LoginPassword = Password.Text;
			//Gl.CurUser.Update();

			AddMessage("Password successfully reset.");
			Response.Redirect("~/default.aspx");
		}



        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
			//FormsAuthentication.SetAuthCookie(UserName.Text, false /* createPersistentCookie */);

            string continueUrl = _continueUrl;
            if (String.IsNullOrEmpty(continueUrl))
            {
                continueUrl = "~/";
            }
            Response.Redirect(continueUrl);
        }

    }
}
